package com.xiaohe.gulimall.member.interceptor;

import com.xiaohe.common.constant.AuthServerConstant;
import com.xiaohe.common.vo.MemberResponseVo;
import org.springframework.stereotype.Component;
import org.springframework.util.AntPathMatcher;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

@Component
public class LoginUserInterceptor implements HandlerInterceptor {

    private static ThreadLocal<MemberResponseVo> threadLocal = new ThreadLocal<>();

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        String requestURI = request.getRequestURI();
        boolean match = new AntPathMatcher().match("/order/order/status/**", requestURI);
        if(match){
            return true;
        }
        boolean matchMember = new AntPathMatcher().match("/member/**", requestURI);
        if (matchMember){
            return true;
        }

        MemberResponseVo user = (MemberResponseVo) request.getSession().getAttribute(AuthServerConstant.LOGIN_USER);
        if(user !=null){
            threadLocal.set(user);
            return true;
        }else {
            request.getSession().setAttribute("msg","请先进行登录");
            response.sendRedirect("http://auth.gulimall.com/login.html");
            return false;
        }
    }

    public static MemberResponseVo getLoginUser(){
        MemberResponseVo memberResponseVo = threadLocal.get();
        return memberResponseVo;
    }
}
